﻿using System;
using System.Collections.Generic;

namespace YudiStudio.VSTO.CardClock.Utilities
{
	public class CardClockHelper
	{
		public static string LastErrorInfo { get; set; }
		public static string ConfigPath { get; set; } = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.txt");
		public static List<Entities.CardClockTcpInfo> GetCardClockTcpInfos()
		{
			try
			{
				return System.IO.File.Exists(ConfigPath) ? Conver.Json.ToList<Entities.CardClockTcpInfo>(FileHelper.TextRead(ConfigPath)) : default;
			}
			catch(Exception ex)
			{
				LastErrorInfo = ex.ToString();
				return default;
			}			
		}
		public static void SetCardClockTcpInfo(List<Entities.CardClockTcpInfo> list)
		{
			try
			{
				FileHelper.TextWrite(ConfigPath, Conver.Object.ToJson(list));
			}
			catch(Exception ex)
			{
				LastErrorInfo = ex.ToString();
			}
		}

		public static List<Library.EastRiver.RecordContent> GetERRecords(Entities.CardClockTcpInfo cardClockTcpInfo) => new Library.EastRiver.TcpIpCardClockHelper()
		{
			ClockID = int.Parse(cardClockTcpInfo.ClockId),
			IPAddress = cardClockTcpInfo.IPAddress,
			IPPort = int.Parse(cardClockTcpInfo.Port)
		}.GetBatchRecord();

		public static List<Library.ZKTeco.ZKTecoCardClockData> GetZKTecoCardClockDatas(Entities.CardClockTcpInfo cardClockTcpInfo) => new Library.ZKTeco.ZKTecoHelper()
		{
			IPAddress = cardClockTcpInfo.IPAddress,
			Port = int.Parse(cardClockTcpInfo.Port)
		}.ClockData_Read();

		public static void ReadData(string clockId, Microsoft.Office.Interop.Excel.Application excel)
		{
			var lstCardClockinfo = GetCardClockTcpInfos().FindAll(info => info.ClockId == clockId);
			if (lstCardClockinfo?.Count > 0)
			{
				Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excel.Workbooks.Add(true);
				Microsoft.Office.Interop.Excel.Worksheet excelWorkSheet = excelWorkbook.Worksheets.Add();
				excelWorkSheet.Activate();
				if (lstCardClockinfo[0].Brand == "依时利")
				{
					var data = GetERRecords(lstCardClockinfo[0]);
					if (data?.Count > 0)
					{
						excelWorkSheet.Range[1, 1].Resize[10, data.Count].Value = excel.WorksheetFunction.Transpose(data.ToArray());
					}
				}
				else if(lstCardClockinfo[0].Brand == "中控")
				{
					var data = GetZKTecoCardClockDatas(lstCardClockinfo[0]);
					if (data?.Count > 0)
					{
						excelWorkSheet.Range[1, 1].Resize[10, data.Count].Value = excel.WorksheetFunction.Transpose(data.ToArray());
					}
				}
			}
		}
	}
}
